package com.mediacloud.app.newsmodule.view

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.mediacloud.app.appointment.AppointmentManager
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.AppointmentController
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.utils.RxUtils
import com.mediacloud.app.view.XSmartRefreshLayout
import kotlinx.android.synthetic.main.hebei_x_microlive_detail.progressBar
import org.json.JSONArray
import org.json.JSONObject
import java.util.ArrayList
import java.util.HashMap

/**
 * 直播预约弹框
 * @property liveRv RecyclerView?
 * @property adapter ListAdapter?
 * @constructor
 */
class AppointmentLiveDialog(context: Context) :
    BottomSheetDialog(context, R.style.MBottomSheetDialog) {


    var liveRv: RecyclerView? = null
    var adapter: ListAdapter? = null

    var index = 1

    var refresh: XSmartRefreshLayout? = null

    var appointmentController: AppointmentController? = null


    init {
        setCancelable(false)
        var view = View.inflate(context, R.layout.dialog_appointment_live, null)
        setContentView(view)
        val layoutRoot = view.findViewById<View>(R.id.layoutRoot)
        var ivClose = view.findViewById<View>(R.id.ivClose)
        refresh = view.findViewById(R.id.refresh)
        liveRv = view.findViewById(R.id.liveRv)
        liveRv?.layoutManager = LinearLayoutManager(context)
        adapter = ListAdapter()
        liveRv?.adapter = adapter
        ivClose.setOnClickListener { dismiss() }

        refresh?.setOnRefreshListener {
            index = 1
            getData(index)
        }
        refresh?.setOnLoadMoreListener {
            index++
            getData(index)
        }

        adapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as ArticleItem
            NewsItemClickUtils.OpenItemNewsHandle(context, item.type, item, CatalogItem())
        }

        adapter?.setOnItemChildClickListener { adapter, view, position ->
            val articleItem = adapter.getItem(position) as ArticleItem
            val startTime =
                JSONObject(articleItem.appCustomParams).optJSONObject("movie")?.optString("startTime")

            val endTime =
                JSONObject(articleItem.appCustomParams).optJSONObject("movie")?.optString("endTime")
            when (view.id) {
                R.id.appointmentState -> {
                    appointmentController?.Appointment(
                        "${articleItem?.id}", "${articleItem?.title}", 15, startTime, endTime, "0"
                    )
                }
            }
        }

        getData(index)

        appointmentController =
            AppointmentController(getContext(), object : AppointmentController.AppointmentStatusListener {
                override fun onAppointmentStatus(contentId: String?, appointmented: Boolean) {
                }

                override fun onAppointmentOk(
                    contentId: String?, appointmented: Boolean, count: Long
                ) {
                    adapter?.notifyDataSetChanged()

                }

                override fun onAppointmentErr(msg: String?) {

                }

            })
    }

    @SuppressLint("CheckResult")
    private fun getData(mPageIndex: Int) {
        val map: MutableMap<String, Any> = HashMap()
        map["type"] = 15
        map["page"] = mPageIndex
        map["perPage"] = 10
        map["liveStatus"] = 0
        map["referenceFlag"] = "Y"
        map["needQuoteFlag"] = "Y"


        DataInvokeUtil.getZiMeiTiApi().getArticleCmsList(map)
            .compose(RxUtils.schedulersTransformer())
            .subscribe({
                refresh?.finishRefresh()
                refresh?.finishLoadMore()

                var isHasNextPage: Boolean = false

                val tempList: MutableList<ArticleItem> = ArrayList()
                if (it.optBoolean("state")) {

                    var data: JSONObject? = it.optJSONObject("data")
                    val meta: JSONArray? = data?.optJSONArray("meta")

                    val paging: JSONObject? = data?.optJSONObject("paging")
                    paging?.let {
                        isHasNextPage = it.optInt("lastPage", 1) != it.optInt("currentPage", 1)
                    }
                    try {
                        meta?.let {
                            for (i in 0 until it.length()) {
                                val item = ArticleItem.parse(meta.optJSONObject(i))
                                tempList.add(item)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                if (mPageIndex == 1) {
                    adapter?.setNewData(tempList)
                } else {
                    adapter?.addData(tempList)
                }

            }, {
                refresh?.finishRefresh()
                refresh?.finishLoadMore()
                Log.e("wy", "error")
            }, {
                refresh?.finishRefresh()
                refresh?.finishLoadMore()
                Log.e("wy", "error")
            }, {
                refresh?.finishRefresh()
                refresh?.finishLoadMore()
                Log.e("wy", "error")
            })
    }


    inner class ListAdapter :
        BaseQuickAdapter<ArticleItem, BaseViewHolder>(R.layout.dialog_item_live_info) {
        override fun convert(helper: BaseViewHolder, item: ArticleItem) {
            val startTime =
                JSONObject(item.appCustomParams).optJSONObject("movie")?.optString("startTime_format")

            helper.setText(R.id.liveDate, startTime)
            helper.setText(R.id.liveSummary, item.title)
            helper.addOnClickListener(R.id.appointmentState)

            val appointmentState = helper.getView<ImageView>(R.id.appointmentState)
            appointmentState.isSelected = AppointmentManager.isAppointment("${item.id}", "0")

        }

    }
}